import React, { Component } from "react";
import axios from "axios";
import PubSub from "pubsub-js";

export default class HeroList extends Component {
    state = {
        heros: [] //用来保存所有的英雄数据
    }
    render() {
        return (
            <div className="hero-list">
                {this.state.heros.map((item) => {
                    return (
                        <div className="item" key={item.id}>
                            <img
                                width="100%"
                                src={"http://cdn.xiaohigh.com" + item.image}
                                alt=""
                            />
                            <p>{item.name}</p>
                        </div>
                    );
                })}
            </div>
        );
    }
    //
    async componentDidMount() {
        //获取所有的英雄数据
        let result = await axios.get('http://api.xiaohigh.com/heros');
        this.setState({
            heros: result.data 
        });

        //订阅频道
        PubSub.subscribe('keyword', async (channel, data) => {
            let result = await axios.get('http://api.xiaohigh.com/heros', {
                params: { 
                    q: data
                }
            });
            this.setState({
                heros: result.data
            })
        });
    }

    //生命周期钩子  组件将要卸载
    componentWillUnmount(){
        PubSub.unsubscribe('keyword');
    }
}
